//
//  AddPlanViewController.m
//  LittleFairyPoet
//
//  Created by rimi on 15/9/10.
//  Copyright (c) 2015年 周林. All rights reserved.
//

#import "WPAddPlanViewController.h"
#import "WPDatePickView.h"
#import "DirectoryViewController.h"
#import "WPAddPlanViewModel.h"
#import "Plan.h"
#import <ReactiveCocoa.h>
#import "TopViewModel.h"

static NSString *const kUITableViewCellIdentifier = @"newPlanCellIdentifier";

@interface WPAddPlanViewController ()<UITextFieldDelegate, UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) UILabel * timeLabel;
@property (nonatomic, strong) UITextField * timeTextField;
@property (nonatomic, strong) UILabel * taskLabel;
@property (nonatomic, strong) UIButton * addButton;
@property (nonatomic, strong) UITableView * newPlanTableView;
@property (nonatomic, strong) NSMutableArray * planDataSource;
@property (nonatomic, strong) UILabel * topLabel;
@property (nonatomic, strong) UITextField * topTextField;
@property (nonatomic, strong) UISwitch * topSwitch;


- (void)initializeDataSource; /**< 初始化数据源 */
- (void)initializeUserInterface; /**< 初始化用户界面 */

@end

@implementation WPAddPlanViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initializeUserInterface];
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self initializeDataSource];
    [self.newPlanTableView reloadData];
}
#pragma mark - private methods
- (void)initializeDataSource {
    if (self.planDataSource.count > 0) {
        [self.newPlanTableView reloadData];
        return;
    }
    if (self.model.peoms.count > 0) {
        self.planDataSource = [NSMutableArray arrayWithArray:self.model.peoms];
    }
    [self.newPlanTableView reloadData];
}
- (void)initializeUserInterface {
    self.view.backgroundColor = [UIColor whiteColor];
    self.titleLable.text = @"添加学习计划";
    [self.rightButton setTitle:@"保存" forState:UIControlStateNormal];
    [self.rightButton setTitleColor:[UIColor blackColor] forState:UIControlStateSelected];
    [self.rightButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.view addSubview:self.timeLabel];
    [self.view addSubview:self.timeTextField];
    [self.view addSubview:self.topLabel];
    [self.view addSubview:self.topTextField];
    [self.view addSubview:self.topSwitch];
    [self.view addSubview:self.taskLabel];
    [self.view addSubview:self.addButton];
    [self.view addSubview:self.newPlanTableView];
    if (_model) {
        self.timeTextField.text = _model.planTime;
        self.topTextField.text = _model.topTime;
        self.topSwitch.on = _model.topOn;
    }
    
}
#pragma mark - responds events
- (void)respondsToTabBarRightButton:(UIButton *)sender {
    self.model.planTime = self.timeTextField.text;
    self.model.topTime = self.topTextField.text;
    self.model.topOn = self.topSwitch.isOn;
    self.model.peoms = self.planDataSource;
    NSDateFormatter * formattor = [[NSDateFormatter alloc]init];
    formattor.timeZone = [NSTimeZone localTimeZone];
    formattor.dateFormat = @"yyyy年MM月dd日";
    NSDate * date = [NSDate date];
    NSString * timeStr = [formattor stringFromDate:date];
    self.model.createTime = timeStr;
    __weak typeof(self)weakself = self;
    [WPAddPlanViewModel saveNewPlanWithPlan:_model andWithReturnFlag:^(NSInteger flag) {
        if (flag == 0) {
            [weakself initializeAlertControllerWithMessage:@"保存成功" withHandelBlock:^(UIAlertAction * action) {
                [self.navigationController popViewControllerAnimated:YES];
            }];
        }
        else if(flag == 1) {
            [weakself initializeAlertControllerWithMessage:@"保存失败"];
        }
    }];
    
}
- (void)respondsToAddButton {
    DirectoryViewController* findVC = [[DirectoryViewController alloc]init];
    findVC.isFind = YES;
    findVC.planPeoms = [NSMutableArray arrayWithArray:self.planDataSource];
    RAC(self, planDataSource) = RACObserve(findVC, planPeoms);
    [self.navigationController pushViewController:findVC animated:YES];
}
- (void)respondsToSwitch:(UISwitch *)sender {
    if (self.timeTextField.text.length == 0|self.topTextField.text.length < 5) {
        [self initAlertControllerDismissWithMessage:@"请选择学习或提醒时间"];
        return;
    }
    if (sender.isOn) {
        [TopViewModel addLocalNotificationWithPlanTime:self.timeTextField.text andWithTopTime:self.topTextField.text];
    } else {
        [TopViewModel cancelNotification];
    }
}
#pragma mark - 系统协议
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    __weak typeof(self) weakself = self;
    if (textField == self.timeTextField) {
        [WPDatePickView showViewWithTitle:@"计划学习时间" datePickerMode:UIDatePickerModeDate maxDate:nil minDate:nil complete:^(NSDate *date) {
            NSDateFormatter * formattor = [[NSDateFormatter alloc]init];
            formattor.dateFormat = @"yyyy年MM月dd日";
            NSString * timeStr = [formattor stringFromDate:date];
            weakself.timeTextField.text = timeStr;
        }];
    }
    else if (textField == self.topTextField) {
        [WPDatePickView showViewWithTitle:@"提醒时间" datePickerMode:UIDatePickerModeTime maxDate:nil minDate:nil complete:^(NSDate *date) {
            NSDateFormatter * formattor = [[NSDateFormatter alloc]init];
            formattor.dateFormat = @"HH:mm:00";
            NSString * timeStr = [formattor stringFromDate:date];
            weakself.topTextField.text = timeStr;
        }];
    }
    return NO;
}

#pragma mark---协议UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.planDataSource.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kUITableViewCellIdentifier];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:kUITableViewCellIdentifier];
    }
    cell.accessoryType = UITableViewCellAccessoryNone;
    cell.backgroundColor = [UIColor clearColor];
    cell.textLabel.text = self.planDataSource[indexPath.row][@"title"];
    cell.detailTextLabel.text = self.planDataSource[indexPath.row][@"zuozhe"];
    return cell;
}
//删除标题设置
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath {
    return @"删除";
}
//处理删除或者添加逻辑
//在这个方法中可以获取当前选中的indexpath(section, row)
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    [self.planDataSource removeObjectAtIndex:indexPath.row];
    [self.newPlanTableView reloadData];
}
//是否允许拖动
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

#pragma mark - UITableViewDataSource
//设置每一行高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 60;
}
//用户点击了某一行
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
}


#pragma mark - getter
- (UILabel *)timeLabel {
    if (!_timeLabel) {
        _timeLabel = ({
            UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake(0, 100, 100, 30) adjustWidth:YES];
            label.textAlignment = NSTextAlignmentCenter;
            label.text = @"学习时间:";
            label;
        });
    }
    return _timeLabel;
}
- (UITextField *)timeTextField {
    if (!_timeTextField) {
        _timeTextField = ({
            UITextField * textField = [[UITextField alloc]initWithFrame:CGRectMake(110, 100, 200, 30) adjustWidth:YES];
            textField.borderStyle = UITextBorderStyleRoundedRect;
            textField.delegate = self;
            textField.layer.borderWidth = 1;
            textField.layer.cornerRadius = 5;
            textField;
        });
    }
    return _timeTextField;
}
- (UILabel *)taskLabel {
    if (!_taskLabel) {
        _taskLabel = ({
            UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake(0, 180, 100, 30) adjustWidth:YES];
            label.textAlignment = NSTextAlignmentCenter;
            label.text = @"学习任务:";
            label;
        });
    }
    return _taskLabel;
}
- (UIButton *)addButton {
    if (!_addButton) {
        _addButton = ({
            UIButton * btn = [UIButton buttonWithType:UIButtonTypeSystem];
            btn.frame = DHFlexibleFrame(CGRectMake(250, 180, 70, 30), YES);
            [btn setTitle:@"添加" forState:UIControlStateNormal];
            [btn addTarget:self action:@selector(respondsToAddButton) forControlEvents:UIControlEventTouchUpInside];
            btn;
        });
    }
    return _addButton;
}
- (UITableView *)newPlanTableView {
    if (!_newPlanTableView) {
        _newPlanTableView = ({
            UITableView * tableview = [[UITableView alloc]initWithFrame:DHFlexibleFrame(CGRectMake(0, 210, ORIGIN_WIDTH, ORIGIN_HEIGHT-180), NO) style:UITableViewStylePlain];
            tableview.dataSource = self;
            tableview.delegate = self;
            tableview.tableFooterView = [UIView new];
            tableview.pagingEnabled = NO;
            tableview.separatorColor = [UIColor blackColor];
            tableview;
        });
    }
    return _newPlanTableView;
}
- (NSArray *)planDataSource {
    if (!_planDataSource) {
        _planDataSource = [NSMutableArray array];
    }
    return _planDataSource;
}
- (Plan *)model {
    if (!_model) {
        _model = [[Plan alloc]init];
    }
    return _model;
}
- (UILabel *)topLabel {
    if (!_topLabel) {
        _topLabel = ({
            UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake(0, 150, 100, 30) adjustWidth:YES];
            label.textAlignment = NSTextAlignmentCenter;
            label.text = @"学习提醒:";
            label;
        });
    }
    return _topLabel;
}
- (UITextField *)topTextField {
    if (!_topTextField) {
        _topTextField = ({
            UITextField * textField = [[UITextField alloc]initWithFrame:CGRectMake(110, 150, 100, 30) adjustWidth:YES];
            textField.borderStyle = UITextBorderStyleRoundedRect;
            textField.delegate = self;
            textField.layer.borderWidth = 1;
            textField.layer.cornerRadius = 5;
            textField.text = @"提醒时间";
            textField;
        });
    }
    return _topTextField;
}
- (UISwitch *)topSwitch {
    if (!_topSwitch) {
        _topSwitch = ({
            UISwitch * swi = [[UISwitch alloc]initWithFrame:DHFlexibleFrame(CGRectMake(220, 150, 100, 30), YES)];
            [swi addTarget:self action:@selector(respondsToSwitch:) forControlEvents:UIControlEventValueChanged];
            swi;
        });
    }
    return _topSwitch;
}
@end
